package com.sanalkitaplik.admin;

import java.util.ArrayList;

import com.sanalkitaplik.hibernateutil.AdminsUtil;

public class AdminManagerBean {
	
	private Admin admin;
	private boolean error;
	
	private static ArrayList<Admin> onlineUsers = new ArrayList<Admin>();
	
	private AdminGroupsManager adminGroupsManager;
	private AdminAdminsManager adminAdminsManager;
	
	
	public AdminManagerBean() {
		admin = new Admin();
		error = false;
		adminGroupsManager = new AdminGroupsManager();
		adminAdminsManager = new AdminAdminsManager();
	}
	
	public Admin getAdmin() {
		return admin;
	}
	
	public String login() {
		String userName = admin.getUserName();
		String password = admin.getPassword();
		
		error = userName.isEmpty() || password.isEmpty() || AdminsUtil.loginCheck(userName, password);
		
		//if (!error)
			//error = !(userName.equals("admin") && password.equals("admin"));
		if (error) {
			return null;
		}
		for (int i=0; i<AdminManagerBean.onlineUsers.size(); i++) {
			if (AdminManagerBean.onlineUsers.get(i) == this.admin) {
				AdminManagerBean.onlineUsers.remove(i);
				break;
			}
		}
		onlineUsers.add(admin);
		return "adminLoginSuccess";
	}
	
	public boolean getError() {
		return this.error;
	}
	
	public String logOut() {
		beOffline();
		return "adminLoginPanel";
	}
	
	private void beOffline() {
		for (int i=0; i<AdminManagerBean.onlineUsers.size(); i++) {
			if (AdminManagerBean.onlineUsers.get(i).equals(this.admin)) {
				AdminManagerBean.onlineUsers.remove(i);
				return;
			}
		}
	}
	
	protected void finalize() {
		beOffline();
	}
	
	public static boolean isOnline(Admin admin) {
		if (admin == null)
			return false;
		for (int i=0; i<AdminManagerBean.onlineUsers.size(); i++) {
			if (AdminManagerBean.onlineUsers.get(i).equals(admin))
				return true;
		}
		return false;
	}
	
	public void setAdminGroupsManager(AdminGroupsManager adminGroupsManager) {
		this.adminGroupsManager = adminGroupsManager;
	}
	
	public AdminGroupsManager getAdminGroupsManager() {
		return this.adminGroupsManager;
	}
	
	public void setAdminAdminsManager(AdminAdminsManager adminAdminsManager) {
		this.adminAdminsManager = adminAdminsManager;
	}
	
	public AdminAdminsManager getAdminAdminsManager() {
		return this.adminAdminsManager;
	}

}
